package top.infopub.mgr.cap.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.infopub.dto.cap.PayInterestDto;
import top.infopub.enums.hr.PostGroupEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.cap.domain.PayInterestDomain;
import top.infopub.mgr.cap.jsonvo.PayInterestJsonVo;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.PayInterestService;
import top.infopub.mgr.cap.vo.PayInterestQuery;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.cap.PayInterest;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 融资付息
 */
@Controller
@RequestMapping("/payInterest")
public class PayInterestController extends GenericFlowController {
    @Autowired
    private PayInterestService payInterestService;

    @Autowired
    private CapProcessManageService capProcessManageService;

    /**
     * 融资付息列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "cap/lay-payInterest-list";
    }

    /**
     * 融资放款列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<PayInterestDomain> queryDataByCondition(PayInterestQuery query, ParamPage paramPage) {
        PageInfo<PayInterestDomain> page = payInterestService.queryPayInterestPage(paramPage, query);
        return RspVo.getSuccessResponse(page.getTotal(), page.getList());
    }

    /**
     * 根据id查询融资付款详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 融资放款Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public String toDealOrDetail(HttpServletRequest request, String id, String proCode) {
        request.setAttribute("id", id);
        PayInterest payInt = payInterestService.selectByPrimaryKey(id);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");//登录人和审批人一致使用该字段是否显示审核信息
        request.setAttribute("finFlag", "0");//指定财务人员进入审批页面必须填写财务信息
        if (payInt != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), payInt.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), payInt.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(payInt.getProcessId()) && payInt.getProcessId().length() > 10) {
                request.setAttribute("processId", payInt.getProcessId());
                String auditTabFlag = capProcessManageService.checkShowAuditTab(payInt.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), payInt.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                //查询指定财务节点人员ID
                List<String> finUserIdList = capProcessManageService.queryFinanceUserIdByProcessId(payInt.getProcessId(), "-1", PostGroupEnum.FINANCE.getCode());
                if (finUserIdList != null && finUserIdList.size() > 0) {
                    for (String finUserId : finUserIdList) {
                        if (StringUtils.isBlank(finUserId)) continue;
                        if (StringUtils.equals(vo.getId(), finUserId)) {
                            //当前待审批节点=当前登录人，需要编辑财务信息提交
                            request.setAttribute("finFlag", "1");//指定财务人员进入审批页面必须填写财务信息
                        }
                    }
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        request.setAttribute("proCode", proCode);
        return "cap/lay-FinancingInterestPayment-detail";
    }

    @RequestMapping("/queryDetail")
    @ResponseBody
    public RspVo queryDetail(String id) {
        PayInterestJsonVo payIntJson = payInterestService.queryDetailById(id);
        return RspVo.getSuccessResponse(payIntJson);
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String processId, String status, String auditMsg, PayInterest payInterest) {
        //融资付息审批
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        List<String> finUserIdList = capProcessManageService.queryFinanceUserIdByProcessId(processId, "-1", PostGroupEnum.FINANCE.getCode());
        if (finUserIdList != null && finUserIdList.size() > 0) {
            for (String finUserId : finUserIdList) {
                if (StringUtils.isBlank(finUserId)) continue;
                if (StringUtils.equals(vo.getId(), finUserId)) {
                    //当前待审批节点=当前登录人，需要编辑财务信息提交
                    if (payInterest == null || payInterest.getActualPayAmt() == null
                            || payInterest.getPaymentDate() == null
                            || StringUtils.isBlank(payInterest.getBankName())
                            || StringUtils.isBlank(payInterest.getAccountNo())) {
                        return RspVo.getFailureResponse(401, "财务还款情况不能为空");
                    }
                    RspVo rspVo = payInterestService.modifyFinInfo(payInterest, vo, processId);
                    if (!rspVo.isSuccess()) return rspVo;
                    break;
                }
            }
        }
        capProcessManageService.auditProject(payInterest.getId(), processId, status, auditMsg);
        return RspVo.getSuccessResponse();
    }

    /**
     * 编辑融资付息
     * @param bodyStr json数据
     * @param submitType 0=保存，1=提交
     * @return
     */
    @RequestMapping("/edit")
    public @ResponseBody RspVo edit(String bodyStr, Integer submitType) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String str = StringEscapeUtils.unescapeJava(bodyStr);
        PayInterestJsonVo payIntJson = JSON.parseObject(str, PayInterestJsonVo.class);
        PayInterestDto payIntDto = payIntJson.getInfo();

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(payIntJson.getFileAtt()!=null){
            String[] fileAtt = payIntJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo, payIntDto.getId(), file);
                attachmentList.add(attachment);
            }
        }
        RspVo rspVo = payInterestService.edit(payIntDto, payIntJson.getDetailList(), attachmentList, submitType, vo);
        return rspVo;
    }

    /**
     * 上传附件
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    @ResponseBody
    public RspVo updateAtt(HttpServletRequest request) {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        if (fileMap != null) {
            for (String name : fileMap.keySet()) {
                MultipartFile file = fileMap.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                //上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                //服务器资源路径
                String serverPath = "loanFinAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add("|" + file.getOriginalFilename().trim() + "|" + fileId + "|"
                        + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传融资放款附件-文件名:" + filePath
                        + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }
}
